<template>
  <el-select
    :value="selectedValues"
    placeholder="请选择"
    multiple
    filterable
    remote
    :remote-method="handleRemoteMethod"
    @visible-change="handleSelectVisibleChange"
    ref="selectRef"
    @input="updateSelectedValues"
    :multiple-limit="multipleLimit"
    :disabled="isDisabled"
    :collapse-tags="isCollapsed"
  >
    <el-option
      v-for="item in displayedOptionsVal"
      :key="item.id"
      :label="`${item.deviceName}`"
      :value="item.deviceName"
    />
  </el-select>
</template>

<script>
export default {
  name: "SelectWithScroll",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    list: {
      type: Array,
      default: () => [],
    },
    labelNew: {
      type: String,
    },
    multipleLimit: {
      type: String,
    },
    isDisabled: {
      type: Boolean,
    },
    isCollapsed: {
      type: Boolean,
    },
  },

  watch: {
    list: {
      handler(newVal) {
        this.allOptions = newVal;
        let selVAL = newVal.filter((item) => {
          return this.value.includes(item.deviceSn);
        });
        this.displayedOptions = [...this.displayedOptions, ...selVAL];
        this.loadMoreOptions();
      },
      deep: true,
      immediate: true,
    },
    query: {
      handler(newVal) {
        this.currentPage = 1;
        this.displayedOptions = [];
        // this.loadMoreOptions();
        setTimeout(() => {
          this.loadMoreOptions();
        }, 500);
      },
      immediate: true,
    },
  },

  data() {
    return {
      allOptions: [], // 存储所有选项数据
      displayedOptions: [], // 存储当前显示的选项数据
      currentPage: 1,
      pageSize: 100,
      query: "",
      isSelectedValuesLoaded: false, // 控制是否已加载已选中的值
    };
  },
  computed: {
    selectedValues: {
      get() {
        return this.value;
      },
      set(newValue) {
        this.$emit("input", newValue);
      },
    },
    displayedOptionsVal() {
      return this.displayedOptions.filter((device, index, arr) => {
        return index === arr.findIndex((d) => d.deviceSn === device.deviceSn);
      });
    },
  },
  mounted() {
    // console.log(this.value);
    // console.log(this.list);
    // this.fetchAllOptions();
    // // 模拟从后端获取已选中的值，实际项目中可以通过接口获取
    // setTimeout(() => {
    //   // this.selectedValues = ['1', '2'];
    //   this.isSelectedValuesLoaded = true;
    // }, 1000);
  },
  methods: {
    // 模拟从后端获取所有选项数据
    // fetchAllOptions() {
    //   // 这里应该是从后端获取所有选项数据的逻辑
    //   // 模拟生成 1000 条数据
    //   const allData = Array.from({ length: 1000 }, (_, index) => ({
    //     value: String(index + 1),
    //     label: `选项 ${index + 1}`,
    //   }));
    //   this.allOptions = allData;
    //   this.loadMoreOptions();
    // },
    // 加载更多选项
    loadMoreOptions() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      console.log("query", this.query);
      const options = this.allOptions.filter((item) => {
        return item.deviceName.toLowerCase().includes(this.query.toLowerCase());
      });
      console.log("options", options);
      const pageData = options.slice(startIndex, endIndex);
      this.displayedOptions = [...this.displayedOptions, ...pageData];

      // 如果已加载了已选中的值且当前显示的选项中不包含已选中的值，将它们添加到显示的选项中
      if (this.isSelectedValuesLoaded) {
        this.ensureSelectedValuesAreDisplayed();
      }
    },
    // 确保已选中的值在显示的选项中
    ensureSelectedValuesAreDisplayed() {
      this.selectedValues.forEach((value) => {
        const option = this.allOptions.find((item) => item.value === value);
        if (
          option &&
          !this.displayedOptions.some((item) => item.value === value)
        ) {
          this.displayedOptions.unshift(option); // 将已选中的值添加到显示的选项的开头
        }
      });
    },
    // 处理远程查询方法
    handleRemoteMethod(query) {
      console.log(query);

      this.query = query;
      // this.currentPage = 1;
      // this.displayedOptions = [];
      // 根据查询条件筛选所有选项
      // const filteredOptions = this.allOptions.filter((item) => {
      //   return item.deviceName.toLowerCase().includes(query.toLowerCase());
      // });
      // 更新显示的选项为筛选后的结果
      // this.displayedOptions = filteredOptions;

      // console.log(this.displayedOptions);

      this.loadMoreOptions();
    },
    // 处理下拉框显示状态变化
    handleSelectVisibleChange(isVisible) {
      if (isVisible) {
        // 在下拉框显示时，开始监听滚动事件
        this.$nextTick(() => {
          const dropdownElement =
            this.$refs.selectRef.$refs.popper.$el.querySelector(
              ".el-scrollbar__wrap"
            );
          if (dropdownElement) {
            dropdownElement.addEventListener("scroll", this.handleScroll);
          }
        });
      } else {
        // 在下拉框隐藏时，移除滚动事件监听
        const dropdownElement =
          this.$refs.selectRef.$refs.popper.$el.querySelector(
            ".el-scrollbar__wrap"
          );
        if (dropdownElement) {
          dropdownElement.removeEventListener("scroll", this.handleScroll);
        }
      }
    },
    // 处理滚动事件
    handleScroll(event) {
      const { scrollTop, scrollHeight, clientHeight } = event.target;
      // 判断是否滚动到底部
      if (scrollTop + clientHeight >= scrollHeight - 5) {
        // 5 是一个容差值，可以根据需要调整
        // 检查是否还有更多数据可以加载
        const totalLoadedOptions = this.displayedOptions.length;
        const totalOptions = this.allOptions.length;
        if (totalLoadedOptions < totalOptions) {
          this.currentPage++;
          this.loadMoreOptions();
        }
      }
    },
    // 向父组件传递选中的值
    updateSelectedValues(newValue) {
      this.selectedValues = newValue;
    },
  },
};
</script>
